//
//  PurchaseViewController.m
//  ApplePayTest
//
//  Created by tiger on 16/4/19.
//  Copyright © 2016年 宋伟青. All rights reserved.
//

#import "PurchaseViewController.h"
#import "InAppPurchaseViewCell.h"
#import <StoreKit/StoreKit.h>

@interface PurchaseViewController () <UITableViewDelegate, UITableViewDataSource, SKProductsRequestDelegate, SKPaymentTransactionObserver>
@property (strong, nonatomic) NSArray <SKProduct *> *products;
@property (strong, nonatomic) UITableView *tableView;
@end

@implementation PurchaseViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self setupUI];
    
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"重新购买" style:UIBarButtonItemStylePlain target:self action:@selector(rightBarButtonItemClick)];
    
    NSSet *set = [NSSet setWithObjects:@"com.ApplePayDome.tulongdao", @"com.ApplePayDome.yitianjian", @"com.ApplePayDome.tulongdao2", nil];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:set];
    request.delegate = self;
    [request start];

}

- (void)dealloc {
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];
}

- (void)rightBarButtonItemClick {
    [[SKPaymentQueue defaultQueue] restoreCompletedTransactions];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

- (void)setupUI {
    self.tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    self.tableView.tableFooterView = [UIView new];
    [self.tableView registerNib:[UINib nibWithNibName:@"InAppPurchaseViewCell" bundle:nil] forCellReuseIdentifier:@"products"];
}

- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
    NSLog(@"products=%@", response.products);
    NSLog(@"invalidProductIdentifiers=%@", response.invalidProductIdentifiers);
    self.products = response.products;
    [self.tableView reloadData];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.products.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    InAppPurchaseViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"products" forIndexPath:indexPath];
    cell.textLabel.text = self.products[indexPath.row].localizedTitle;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"￥ %@", self.products[indexPath.row].price];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    SKProduct *product = self.products[indexPath.row];
    // 支付凭证
    SKPayment *payment = [SKPayment paymentWithProduct:product];
    // 添加支付凭证到支付队列
    [[SKPaymentQueue defaultQueue] addPayment:payment];
    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
}

- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions {
    [transactions enumerateObjectsUsingBlock:^(SKPaymentTransaction * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        //  SKPayment *payment , 小票 , 有商品
        //  SKPaymentTransactionState transactionState 交易状态
        switch (obj.transactionState) {
            case  SKPaymentTransactionStatePurchasing:
                NSLog(@"正在付款");
                break;
            case  SKPaymentTransactionStatePurchased:
            {
                NSLog(@"付款结束");
                [queue finishTransaction:obj];
                break;
            }
            case  SKPaymentTransactionStateFailed:
            {
                NSLog(@"交易失败");
                [queue finishTransaction:obj];
                break;
            }
            case  SKPaymentTransactionStateRestored:
                NSLog(@"恢复购买");
                break;
            case SKPaymentTransactionStateDeferred:
                NSLog(@"推迟付款");
                break;
                
            default:
                break;
        }
        
    }];
}


@end
